<?php

// 一键融资
// GET project.keyPush

namespace app\api\resource\project;
use think\Db;
use app\common\logic\KeyPush as KeyPushLogic;

class KeyPush
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = ['login'];
    // 描述
    public $_description = '一键融资';
    // 参数
    public $_param  = [
        'project_id' => '项目主键',
    ];
    // 返回
    public $_return = [
        201 => '一键融资成功',
    ];

    public function run(&$request)
    {
        $projectId = $request->post('project_id/d',0,'abs');

        if (0 == $projectId) return [422,'项目主键必须'];

        $project = Db::name('project')->where('id',$projectId)->find();
        if ( is_null($project) ) return [400,'项目不存在'];

        // 检查项目是否完成评估

        if ( 0 == $project['is_cp'] ) return [400,'项目未完成评估'];
        // 检查项目是否缴纳诚信保证金
        if ( empty($project['is_cx_pay']) ) return [400,'项目未缴纳诚信保证金'];
        // 检查当日一键融资剩余次数
        $n = $this->_check_push_rule($project);
        if (-1 == $n) return [400,'今日一键融资次数已达上限'];

        // 一键融资
        $count = KeyPushLogic::run($project);
        
        $data['surplus'] = $n;
        $data['count']   = $count;
        return [201,$data];
    }

    /**
     * [_check_push_rule description]
     * @param  [type] $project [description]
     * @return [type]          [description]
     */
    private function _check_push_rule($project)
    {
        if ( $project['push_date'] == date('Ymd') ) {
            if ($project['times'] < 3) {
                $data['times'] = ['exp','times + 1'];
                Db::name('project')->where('id',$project['id'])->update($data);
                return (3 - $project['times'] - 1);
            } else {
                return -1;
            }
        } else {
            $data['push_date'] = date('Ymd');
            $data['times']     = 1;
            Db::name('project')->where('id',$project['id'])->update($data);
            return 2;
        }
    }
}